<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>
    <c:choose>
      <c:when test="${not empty order}">编辑进车订单</c:when>
      <c:otherwise>添加新进车订单</c:otherwise>
    </c:choose>
  </title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
  <link rel="stylesheet" href="${pageContext.request.contextPath}/css/purchase.css">
</head>
<body>
<header class="dashboard-header">
  <div class="container">
    <div class="d-flex justify-content-between align-items-center">
      <div>
        <h1 class="h3 mb-0"><i class="bi bi-bicycle"></i> 电动车销售管理系统</h1>
        <p class="mb-0 opacity-75">业务员工作台</p>
      </div>
      <div class="d-flex align-items-center">
        <div class="me-3">
          <span class="d-none d-md-inline">${currentSalesman.name}</span>
          <div class="badge bg-light text-dark">
            <i class="bi bi-person-circle me-1"></i> 业务员
          </div>
        </div>
        <div class="dropdown">
          <button class="btn btn-light rounded-circle p-1" type="button" data-bs-toggle="dropdown">
            <i class="bi bi-gear fs-5"></i>
          </button>
          <ul class="dropdown-menu dropdown-menu-end">
            <li><a class="dropdown-item" href="${pageContext.request.contextPath}/changePassword"><i class="bi bi-lock me-2"></i> 修改密码</a></li>
            <li><hr class="dropdown-divider"></li>
            <li><a class="dropdown-item text-danger" href="logout"><i class="bi bi-box-arrow-right me-2"></i> 退出登录</a></li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</header>

<div class="container">
  <div class="d-flex justify-content-between align-items-center mb-4">
    <div>
      <h2 class="mb-0">
        <c:choose>
          <c:when test="${not empty order}">
            <i class="bi bi-pencil-square me-2"></i>编辑进车订单
          </c:when>
          <c:otherwise>
            <i class="bi bi-plus-lg me-2"></i>添加新进车订单
          </c:otherwise>
        </c:choose>
      </h2>
      <p class="text-muted mb-0">
        <c:choose>
          <c:when test="${not empty order}">
            修改订单 #${order.id} 的详细信息
          </c:when>
          <c:otherwise>
            创建新的车辆采购订单
          </c:otherwise>
        </c:choose>
      </p>
    </div>
    <div>
      <a href="${pageContext.request.contextPath}/purchase/list" class="btn btn-light">
        <i class="bi bi-arrow-left me-1"></i> 返回列表
      </a>
    </div>
  </div>

  <div class="card">
    <div class="card-body">
      <form action="${pageContext.request.contextPath}/purchase/${not empty order ? 'update' : 'save'}" method="post" id="orderForm">
        <c:if test="${not empty order}">
          <input type="hidden" name="id" value="${order.id}">
        </c:if>

        <div class="row">
          <div class="col-md-7">
            <div class="mb-4">
              <h5 class="mb-3"><i class="bi bi-truck me-2"></i>车辆信息</h5>

              <div class="form-group mb-4">
                <label class="form-label fw-medium">选择车辆</label>
                <select class="form-select form-select-lg" name="vehicleId" id="vehicleSelect" required>
                  <option value="">-- 请选择车辆 --</option>
                  <c:forEach items="${vehicles}" var="vehicle">
                    <option value="${vehicle.id}"
                            data-price="${vehicle.price}"
                            data-image="${vehicle.pic}"
                            <c:if test="${not empty order && order.v_id == vehicle.id}">selected</c:if>>
                        ${vehicle.brand} ${vehicle.model} ${vehicle.color} (${vehicle.productionYear}) - ¥${vehicle.price}
                    </option>
                  </c:forEach>
                </select>
              </div>

              <div class="row">
                <div class="col-md-6">
                  <div class="form-group mb-4">
                    <label class="form-label fw-medium">品牌</label>
                    <input type="text" class="form-control" id="brand" readonly>
                  </div>
                </div>
                <div class="col-md-6">
                  <div class="form-group mb-4">
                    <label class="form-label fw-medium">型号</label>
                    <input type="text" class="form-control" id="model" readonly>
                  </div>
                </div>
              </div>

              <div class="row">
                <div class="col-md-6">
                  <div class="form-group mb-4">
                    <label class="form-label fw-medium">颜色</label>
                    <input type="text" class="form-control" id="color" readonly>
                  </div>
                </div>
                <div class="col-md-6">
                  <div class="form-group mb-4">
                    <label class="form-label fw-medium">生产年份</label>
                    <input type="text" class="form-control" id="year" readonly>
                  </div>
                </div>
              </div>

              <div class="form-group mb-4">
                <label class="form-label fw-medium">单价</label>
                <div class="input-group">
                  <span class="input-group-text">¥</span>
                  <input type="text" class="form-control" id="price" readonly>
                </div>
              </div>
            </div>
          </div>

          <div class="col-md-5">
            <div class="mb-4">
              <h5 class="mb-3"><i class="bi bi-card-checklist me-2"></i>订单详情</h5>

              <div class="mb-4 text-center">
                <div class="vehicle-preview mb-3">
                  <img id="vehicleImage" src="${pageContext.request.contextPath}/images/vehicles/default-car.png"
                       class="img-fluid rounded" alt="车辆预览">
                </div>
                <div id="vehicleName" class="fw-medium">未选择车辆</div>
              </div>

              <div class="form-group mb-4">
                <label class="form-label fw-medium">采购数量</label>
                <input type="number" class="form-control form-control-lg"
                       name="quantity" min="1" value="${not empty order ? order.quantity : '1'}" required>
              </div>

              <div class="form-group mb-4">
                <label class="form-label fw-medium">订单状态</label>
                <div class="form-control bg-light">
                  <c:choose>
                    <c:when test="${not empty order && order.status == 1}">
                      <span class="badge bg-success">已审核</span>
                    </c:when>
                    <c:otherwise>
                      <span class="badge bg-warning">待审核</span>
                    </c:otherwise>
                  </c:choose>
                </div>
              </div>

              <div class="form-group mb-4">
                <label class="form-label fw-medium">创建时间</label>
                <input type="text" class="form-control"
                       value="${not empty order ? order.createTime : '--'}" readonly>
              </div>

              <div class="card bg-light border-0 p-3 mb-4">
                <div class="d-flex justify-content-between mb-2">
                  <span>小计:</span>
                  <span id="subtotal">¥0.00</span>
                </div>
                <div class="d-flex justify-content-between mb-2">
                  <span>运费:</span>
                  <span>¥0.00</span>
                </div>
                <div class="d-flex justify-content-between fw-bold fs-5">
                  <span>总计:</span>
                  <span id="total">¥0.00</span>
                </div>
              </div>

              <div class="d-grid">
                <button type="submit" class="btn btn-primary btn-lg">
                  <c:choose>
                    <c:when test="${not empty order}">
                      <i class="bi bi-check-circle me-1"></i> 更新订单
                    </c:when>
                    <c:otherwise>
                      <i class="bi bi-plus-circle me-1"></i> 创建订单
                    </c:otherwise>
                  </c:choose>
                </button>
              </div>
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="${pageContext.request.contextPath}/js/purchase.js"></script>
<script>
  document.addEventListener('DOMContentLoaded', function() {
    const vehicleSelect = document.getElementById('vehicleSelect');
    const vehicleImage = document.getElementById('vehicleImage');
    const vehicleName = document.getElementById('vehicleName');
    const brandInput = document.getElementById('brand');
    const modelInput = document.getElementById('model');
    const colorInput = document.getElementById('color');
    const yearInput = document.getElementById('year');
    const priceInput = document.getElementById('price');
    const subtotal = document.getElementById('subtotal');
    const total = document.getElementById('total');
    const quantityInput = document.querySelector('input[name="quantity"]');

    // 初始化表单
    updateVehicleDetails();

    // 监听车辆选择变化
    vehicleSelect.addEventListener('change', updateVehicleDetails);

    // 监听数量变化
    quantityInput.addEventListener('input', calculateTotal);

    function updateVehicleDetails() {
      const selectedOption = vehicleSelect.options[vehicleSelect.selectedIndex];
      const vehicleText = selectedOption.text;
      const vehiclePrice = parseFloat(selectedOption.dataset.price) || 0;
      const vehiclePic = selectedOption.dataset.image || 'default-car.png';

      // 更新预览
      vehicleImage.src = `${pageContext.request.contextPath}/images/vehicles/${vehiclePic}`;
      vehicleName.textContent = vehicleText || '未选择车辆';
      priceInput.value = vehiclePrice.toFixed(2);

      // 更新车辆详情
      if (vehicleText) {
        const parts = vehicleText.split(' ');
        brandInput.value = parts[0] || '';
        modelInput.value = parts[1] || '';
        colorInput.value = parts[2] || '';

        const yearMatch = vehicleText.match(/\((\d+)\)/);
        yearInput.value = yearMatch ? yearMatch[1] : '';
      } else {
        brandInput.value = '';
        modelInput.value = '';
        colorInput.value = '';
        yearInput.value = '';
      }

      calculateTotal();
    }

    function calculateTotal() {
      const price = parseFloat(priceInput.value) || 0;
      const quantity = parseInt(quantityInput.value) || 0;
      const subtotalValue = price * quantity;

      subtotal.textContent = `¥${subtotalValue.toFixed(2)}`;
      total.textContent = `¥${subtotalValue.toFixed(2)}`;
    }
  });
</script>
</body>
</html>